package org.lex.dbq.view.sql;

import java.sql.SQLException;

import org.lex.dbq.model.jdbc.object.ObjectNode;
import org.lex.dbq.model.jdbc.object.ObjectType;
import org.lex.dbq.model.jdbc.object.TreeUtils;
import org.lex.dbq.model.jdbc.sql.SelectBuilder;

public class QueryDataAction extends BaseSqlAction {
	public QueryDataAction(SqlPane pane) {
		super(pane);
		this.setText("Query Data");
	}

	public void run() {
		ObjectNode node = this.getSelectedNode();
		if (null == node || ObjectType.TABLE != node.getType()) {
			return;
		}

		try {
			String sql = buildQuery(node);
			pane.cmd.setText(sql);
			pane.execute();
		} catch (SQLException e) {
			log.error("", e);
		}
	}

	private String buildQuery(ObjectNode table) throws SQLException {
		String catalogName = TreeUtils.getCatalogName(table);
		String schemaName = TreeUtils.getSchemaName(table);
		String tableName = table.getData();
		SelectBuilder b = new SelectBuilder();
		return b.buildSelectAll(pane.getConnection(), catalogName, schemaName, tableName);
	}
}
